import os
import logging
import csv
from datetime import datetime
from typing import List, Dict, Any

def setup_logger(name: str, log_file: str) -> logging.Logger:
    """设置日志记录器，防止重复添加handler"""
    log_dir = os.path.dirname(log_file)
    if log_dir and not os.path.exists(log_dir):
        os.makedirs(log_dir)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s\n'
        '%(pathname)s:%(lineno)d\n'
        '%(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    # 添加文件handler（防止重复）
    if not any(isinstance(h, logging.FileHandler) and getattr(h, 'baseFilename', None) == os.path.abspath(log_file) for h in logger.handlers):
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
    # 添加控制台handler（防止重复）
    if not any(isinstance(h, logging.StreamHandler) and not isinstance(h, logging.FileHandler) for h in logger.handlers):
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)
    return logger

def ensure_data_dir(data_dir: str) -> None:
    """确保数据目录存在"""
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)

def save_to_csv(data: List[Dict[str, Any]], file_path: str, fieldnames: List[str]) -> None:
    """保存数据到CSV文件"""
    file_exists = os.path.exists(file_path)
    
    with open(file_path, 'a', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        
        # 如果文件不存在，写入表头
        if not file_exists:
            writer.writeheader()
        
        # 写入数据
        writer.writerows(data)

def read_csv(file_path: str) -> List[Dict[str, Any]]:
    """读取CSV文件"""
    if not os.path.exists(file_path):
        return []
    
    with open(file_path, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        return list(reader)

def format_date(date_str: str) -> str:
    """格式化日期字符串"""
    try:
        # 尝试解析日期
        date = datetime.strptime(date_str, '%Y-%m-%d')
        return date.strftime('%Y-%m-%d')
    except ValueError:
        # 如果解析失败，返回当前日期
        return datetime.now().strftime('%Y-%m-%d')

def is_after_draw_time(draw_time: str) -> bool:
    """判断是否超过开奖时间"""
    try:
        current_time = datetime.now().time()
        draw_time = datetime.strptime(draw_time, '%H:%M').time()
        return current_time >= draw_time
    except ValueError:
        return False 